package com.iptv.grape.bu;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

import androidx.fragment.app.FragmentTransaction;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iptv.grape.BaseActivity;
import com.iptv.grape.R;
import com.iptv.grape.RunTimeApplication;
import com.iptv.grape.bu.process.BillAppointmentProc;
import com.iptv.grape.bu.process.TTLPlayProc;
import com.iptv.grape.domain.AssetPlayData;
import com.iptv.grape.domain.AssetPlayDataList;
import com.iptv.grape.domain.BillAppointmentContainer;
import com.iptv.grape.domain.BookmarkList;
import com.iptv.grape.domain.Channel;
import com.iptv.grape.domain.ChannelBill;
import com.iptv.grape.domain.ChannelBillList;
import com.iptv.grape.domain.ChannelDLinkList;
import com.iptv.grape.domain.ChannelRecords;
import com.iptv.grape.domain.ChannelType;
import com.iptv.grape.domain.IListViewShowItem;
import com.iptv.grape.domain.TopMenu;
import com.iptv.grape.domain.UserInfo;
import com.iptv.grape.event.EventArgs;
import com.iptv.grape.event.data.DataProc;
import com.iptv.grape.event.data.LiveData;
import com.iptv.grape.event.msg.InitHotChannelListData;
import com.iptv.grape.net.Entity.LoginData;
import com.iptv.grape.net.Entity.LoginResult;
import com.iptv.grape.net.NetworkService;
import com.iptv.grape.ui.frgmt.LiveMenuFragment;
import com.iptv.grape.ui.frgmt.ChannelBillFragment;
import com.iptv.grape.ui.frgmt.RecommendFragment;
import com.iptv.grape.ui.frgmt.TimeLiveFragment;
import com.iptv.grape.ui.frgmt.VodFragment;
import com.iptv.grape.util.AppConstant;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.ReadJsonFile;
import com.iptv.grape.util.SharedUtil;
import com.iptv.grape.util.ToastUtil;
import com.iptv.grape.video.XMediaPlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

// 当前的整个应用程序的状态对象
// 单实例
public class GrapeContext {

    public static GrapeContext _curGrapeContext = null;
    // 私有构造函数
    private GrapeContext(){
        // 注册事件总线
        EventBus.getDefault().register(this);

    }

    // 单实例
    public static GrapeContext curGrapeContext(){
        if(null==_curGrapeContext ){
            synchronized (GrapeContext.class){
                if(null==_curGrapeContext)
                    _curGrapeContext = new GrapeContext();
            }
        }
        return _curGrapeContext;
    }

    // 屏幕关闭设置事件
    public void screenOff(){
        try {
            if (this.curMediaPlayer != null) {
                if (this.curMediaPlayer.isPlaying()) {
                    this.curMediaPlayer.stop();
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    // 退出全屏时是否停止播放
    private boolean quitFullScreenStopPlay = false;

    public boolean isQuitFullScreenStopPlay() {
        return quitFullScreenStopPlay;
    }

    public void setQuitFullScreenStopPlay(boolean quitFullScreenStopPlay) {
        this.quitFullScreenStopPlay = quitFullScreenStopPlay;
    }

    private BaseActivity curActivity;
    private XMediaPlayer curMediaPlayer;

    // 获得当前活动BaseActivity
    public BaseActivity getCurActivity() {
        return curActivity;
    }
    // 获得当前的活动BaseActivity上的 播放器
    public XMediaPlayer getCurMediaPlayer() {
        return curMediaPlayer;
    }

    // 当前的环境（单播 = U 组播 = M）
    private String curEnvironment="U";
    public String curEnvironment() {
        return this.curEnvironment;
    }

    // 是否正在播放
    private boolean isPlaying = false;
    public boolean isPlaying() {
        return isPlaying;
    }

    // 是否拥有焦点
    // 默认false 一开始显示H5 按钮事件全部都给H5
    private boolean isFocus = false;
    public boolean isFocus() {
        return isFocus;
    }
    // 是否正在全屏播放
    private boolean isFullScreen = false;
    public boolean isFullScreen() {
        return isFullScreen;
    }

    // 当前的播放界面类型(直播 = Live 点播 = Vod)
    private String curPlayType="Live";
    public String curPlayType() {
        return this.curPlayType;
    }
    public void setCurPlayType(String playType) {
        this.isPlaying = true;
        this.curPlayType = playType;
    }

    public String getCurPlayType(){
        return this.curPlayType;
    }

    // 当前的直播状态 Live = 直播流 时移 = Time 回看 = Back
    private String curLiveType="Live";
    public String curLiveType() {
        return this.curLiveType;
    }

    public void setCurLiveType(String curLiveType) {
        this.isPlaying = true;
        this.curLiveType = curLiveType;
    }

    // 是否显示的点播的进度条
    private boolean isShowVodMenu = false;
    public boolean isShowVodMenu(){
        return isShowVodMenu;
    }

    // 是否显示了直播的频道菜单
    private boolean isShowLiveMenu = false;
    public boolean isShowLiveMenu() {
        return this.isShowLiveMenu;
    }
    // 是否显示了直播的回看列表菜单
    private boolean isShowChannelBillUI = false;
    public boolean isShowChannelBillUI() {
        return this.isShowChannelBillUI;
    }
    // 是否显示了直播的推荐菜单
    private boolean isShowRecommendUI = false;
    public boolean isShowRecommendUI() {
        return this.isShowRecommendUI;
    }
    public void setShowRecommendUI(boolean isShowRecommendUI) {
         this.isShowRecommendUI = isShowRecommendUI;
    }

    // 是否显示了时移进度条
    private boolean isTimeLiveUI = false;
    public boolean isTimeLiveUI() {
        return this.isTimeLiveUI;
    }

    // 是否正在输入按键换台的模式
    private boolean isChangingLive = false;
    public boolean isChangingLive() {
        return isChangingLive;
    }
    public void setChangingLive(boolean changingLive) {
        isChangingLive = changingLive;
    }

    // 直播的频道菜单Fragment对象
    LiveMenuFragment liveMenuFragment = null;
    // 回看界面
    ChannelBillFragment channelBillFragment = null;
    // 点播的进度条界面
    VodFragment vodFragment = null;
    // 直播底部推荐
    RecommendFragment recommendFragment = null;
    // 时移底部进度条
    TimeLiveFragment timeLiveFragment = null;

    // 加载时移界面UI
    public void loadTimeLiveFragment(BaseActivity activity){
        if(timeLiveFragment == null) {
            timeLiveFragment = TimeLiveFragment.newInstance();
            FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.rel_hk, timeLiveFragment, "timeLiveFragment");
            transaction.commitAllowingStateLoss();
        }else{
            activity.getSupportFragmentManager().beginTransaction().show(timeLiveFragment)
                    .commitAllowingStateLoss();
        }

        isTimeLiveUI = true;
        reSetTimeByAutoClose();
        //AppLog.getCurLog().out("加载直播底部推荐");
    }

    // 隐藏时移界面UI
    public void hideTimeLiveFragment(BaseActivity activity){
        if(timeLiveFragment != null && isTimeLiveUI) {
            activity.getSupportFragmentManager().beginTransaction().hide(timeLiveFragment).commitAllowingStateLoss();
            isTimeLiveUI = false;
            AppLog.getCurLog().out("隐藏时移进度条");
            closeHandle();
        }
    }

    // 显示时移界面UI
    public void showTimeLiveFragment(BaseActivity activity){
        activity.getSupportFragmentManager().beginTransaction().show(timeLiveFragment)
                .commitAllowingStateLoss();

        isTimeLiveUI = true;
        reSetTimeByAutoClose();
    }

    // 移除时移界面UI
    public void removeTimeLiveFragment(BaseActivity activity){
        if(timeLiveFragment != null) {
            activity.getSupportFragmentManager().beginTransaction().remove(timeLiveFragment)
                    .commitAllowingStateLoss();
            isTimeLiveUI = false;
            timeLiveFragment = null;
            AppLog.getCurLog().out("移除时移界面Fragment");
            closeHandle();
        }
    }

    // 加载直播底部推荐
    public void loadRecommendFragment(BaseActivity activity){
        if(recommendFragment == null) {
            recommendFragment = RecommendFragment.newInstance();
            FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.rel_hk, recommendFragment, "recommendFragment");
            transaction.commitAllowingStateLoss();
        }else{
            activity.getSupportFragmentManager().beginTransaction().show(recommendFragment)
                    .commitAllowingStateLoss();
        }
        isShowRecommendUI = true;
        reSetTimeByAutoClose();
        AppLog.getCurLog().out("加载直播底部推荐");
    }
    // 隐藏直播底部推荐
    public void hideRecommendFragment(BaseActivity activity){
        if(recommendFragment != null && isShowRecommendUI) {
            activity.getSupportFragmentManager().beginTransaction().hide(recommendFragment).commitAllowingStateLoss();
            isShowRecommendUI = false;
            closeHandle();
        }
    }

    // 加载点播菜单
    public void loadVodFragment(BaseActivity activity){
        if(vodFragment == null) {
            vodFragment = VodFragment.newInstance();
            FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.rel_hk, vodFragment, "vodFragment");
            transaction.commitAllowingStateLoss();
        }else{
            activity.getSupportFragmentManager().beginTransaction().show(vodFragment)
                    .commitAllowingStateLoss();
        }
        isShowVodMenu = true;
        reSetTimeByAutoClose();

        AppLog.getCurLog().out("显示点播的频道菜单");
    }
    // 隐藏点播菜单
    public void hideVodFragment(BaseActivity activity){
        if(vodFragment != null && isShowVodMenu) {
            activity.getSupportFragmentManager().beginTransaction().hide(vodFragment).commitAllowingStateLoss();
            isShowVodMenu = false;
            closeHandle();
        }
    }

    // 移除点播菜单
    public void removeVodFragment(BaseActivity activity){
        if(vodFragment != null) {
            activity.getSupportFragmentManager().beginTransaction().remove(vodFragment).commitAllowingStateLoss();
            isShowVodMenu = false;
            vodFragment = null;
        }
        //closeHandle();
    }

    private String curInputNum;

    public void setCurInputNum(String curInputNum) {
        this.curInputNum = curInputNum;
    }
    public String getCurInputNum(){
        return this.curInputNum;
    }
    public void addCurInputNum(String addString) {
        //String str = String.valueOf(this.curInputNum) + String.valueOf(curInputNum);
        //this.curInputNum = Integer.parseInt(str);
        this.curInputNum += addString;
    }

    // 按键换台的Handle
    private Handler changingLiveHandle = new Handler();

    private Runnable changingLiveRunnable = new Runnable() {

        @Override
        public void run() {
            int numNo = Integer.parseInt(GrapeContext.curGrapeContext().getCurInputNum());
            Channel channel = GrapeContext.curGrapeContext().getChannelDLinkList().findChannelByNo(numNo);
            String channelID= GrapeContext.curGrapeContext().getChannelDLinkList().getChannelHis().getCurPlayChannel().getChannelID();

            if(channel!=null){
                String keyID =channel.getKeyID();
                if(!TextUtils.isEmpty(channelID)&&channelID.equals(keyID)) {
                    ToastUtil.show("当前频道正在播放中");
                    GrapeContext.curGrapeContext().getCurActivity().hideChangingLiveUI();
                    GrapeContext.curGrapeContext().setChangingLive(false);
                    return;
                }
            }


            if(channel != null){
                LiveData quitLiveData = new LiveData(GrapeContext.this.getChannelDLinkList().getCurChannel(),"2",
                        "23","1");
                EventBus.getDefault().post(new EventArgs(AppConstant.DataLive, AppConstant.DataAcquisition,quitLiveData));



                if( GrapeContext.curGrapeContext().curLiveType().equals("Back")){
                    GrapeContext.curGrapeContext().removeChannelBillUI( GrapeContext.curGrapeContext().getCurActivity());
                }
                if( GrapeContext.curGrapeContext().curLiveType().equals("Time")){
                    GrapeContext.curGrapeContext().removeTimeLiveFragment(GrapeContext.curGrapeContext().getCurActivity());
                }
                GrapeContext.curGrapeContext().setCurPlayType("Live");
                GrapeContext.curGrapeContext().setCurLiveType("Live");
                channel.playChannel();

                LiveData liveData = new LiveData(channel,"2","23","0");
                EventBus.getDefault().post(new EventArgs(AppConstant.DataLive, AppConstant.DataAcquisition,liveData));
                GrapeContext.curGrapeContext().getCurActivity().hideChangingLiveUI();
            }else {
                GrapeContext.curGrapeContext().getCurActivity().NoFindNo();
            }

            GrapeContext.curGrapeContext().setChangingLive(false);
        }
    };

    public void startChangingLiveHandle(){
        changingLiveHandle.removeCallbacks(changingLiveRunnable);
        changingLiveHandle.postDelayed(changingLiveRunnable, 3 * 1000);
//        if(isChangingLive) {
//            changingLiveHandle.postDelayed(changingLiveRunnable, 3 * 1000);
//        }
    }
    public void removeChangingLiveHandle(){
        changingLiveHandle.removeCallbacks(changingLiveRunnable);
    }




    private Handler autoHandle = new Handler();

    private Runnable autoHandleRunnable = new Runnable() {

        @Override
        public void run() {
            if(isShowLiveMenu){
                hiddLiveMenu(curActivity);
            }
            if(isShowVodMenu){
                hideVodFragment(curActivity);
            }
            if(isShowRecommendUI){
                hideRecommendFragment(curActivity);
            }
            if(isTimeLiveUI){
                hideTimeLiveFragment(curActivity);
            }
            if(isShowChannelBillUI){
                hiddChannelBillUI(curActivity);
            }
        }
    };

    public void closeHandle(){
        autoHandle.removeCallbacks(autoHandleRunnable);
    }

    public void reSetTimeByAutoClose(){
        if(AppConstant.IsAutoCloseOpen) {
            autoHandle.removeCallbacks(autoHandleRunnable);
            if (isShowLiveMenu || isShowVodMenu || isShowRecommendUI || isTimeLiveUI || isShowChannelBillUI) {
                autoHandle.postDelayed(autoHandleRunnable, AppConfig.getAppConfig().getAutoCloseMenuTime() * 1000);
            }
        }
    }

    // 加载直播频道菜单 如不存在则加载Fragment对象
    public void loadLiveMenu(BaseActivity activity){
        loadLiveMenu(activity,-1);
    }
    // 加载直播频道菜单 如不存在则加载Fragment对象
    public void loadLiveMenu(BaseActivity activity,int selectIndex){
        if(liveMenuFragment == null) {
            liveMenuFragment = LiveMenuFragment.newInstance();
            if(selectIndex >= 0){
                liveMenuFragment.setSelectIndex(selectIndex);
                liveMenuFragment.setNeedSetSelectIndex(true);
            }
            else {
                liveMenuFragment.setSelectIndex(-1);
                liveMenuFragment.setNeedSetSelectIndex(false);
            }
            FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.container, liveMenuFragment, "liveMenuFragment");
            transaction.commitAllowingStateLoss();

        }else{
            if(selectIndex >= 0){
                liveMenuFragment.setSelectIndex(selectIndex);
                liveMenuFragment.setNeedSetSelectIndex(true);
            }
            else {
                liveMenuFragment.setSelectIndex(-1);
                liveMenuFragment.setNeedSetSelectIndex(false);
            }
            activity.getSupportFragmentManager().beginTransaction().show(liveMenuFragment)
                    .commitAllowingStateLoss();
        }
        isShowLiveMenu = true;
        reSetTimeByAutoClose();
        AppLog.getCurLog().out("显示直播的频道菜单");

    }
    // 隐藏直播频道菜单
    public void hiddLiveMenu(BaseActivity activity){
        activity.getSupportFragmentManager().beginTransaction().hide(liveMenuFragment).commitAllowingStateLoss();

        isShowLiveMenu = false;
        closeHandle();
    }
    // 加载节目单UI
    // dateTime = 回看的日期
    public void loadChannelBillUI(BaseActivity activity,String dateTimeString,ChannelBill bill,int pos,
                                  List<IListViewShowItem> dataSouce){
        if(channelBillFragment == null) {
            channelBillFragment = ChannelBillFragment.newInstance(dateTimeString);
            channelBillFragment.setSelectBill(bill);
            channelBillFragment.setSelectIndex(pos);
            List<ChannelBill> channelBills = new ArrayList<ChannelBill>();
            for(int i = 0; i < dataSouce.size(); i++){
                channelBills.add((ChannelBill)dataSouce.get(i));
            }
            channelBillFragment.setChannelBills(channelBills);
            FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.rel_hk, channelBillFragment, "channelBillFragment");
            transaction.commitAllowingStateLoss();
        }else{
            activity.getSupportFragmentManager().beginTransaction().show(channelBillFragment)
                    .commitAllowingStateLoss();
        }
        isShowChannelBillUI = true;
        reSetTimeByAutoClose();
    }
    // 隐藏节目单UI
    public void hiddChannelBillUI(BaseActivity activity){
        if(channelBillFragment != null) {
            activity.getSupportFragmentManager().beginTransaction().hide(channelBillFragment).commitAllowingStateLoss();
            isShowChannelBillUI = false;
            closeHandle();
        }
    }
    // 再次显示节目单
    public void showChannelBillUI(BaseActivity activity){
        activity.getSupportFragmentManager().beginTransaction().show(channelBillFragment)
                .commitAllowingStateLoss();
        isShowChannelBillUI = true;
        reSetTimeByAutoClose();
    }
    // 移除节目单碎片
    public void removeChannelBillUI(BaseActivity activity){
        if(channelBillFragment != null) {
            activity.getSupportFragmentManager().beginTransaction().remove(channelBillFragment)
                    .commitAllowingStateLoss();
            isShowChannelBillUI = false;
            channelBillFragment = null;
            closeHandle();
        }
    }

    // 应用程序状态比较
    public boolean isEqualAppState(AppState appState){
        boolean rtVal = this.isShowLiveMenu == appState.isShowLiveMenu()
                && this.isFullScreen == appState.isFullScreen()
                && this.isFocus == appState.isFocus()
                && ("ALL".equals(appState.curLiveType()) || this.curLiveType.equals(appState.curLiveType()))
                && this.isPlaying == appState.isPlaying()
                && (appState.isIgnoreShowChannelBillUI() || this.isShowChannelBillUI == appState.isShowChannelBillUI())
                && (appState.isIgnoreShowVodMenu() || this.isShowVodMenu == appState.isShowVodMenu())
                && (appState.isIgnoreShowRecommendUI() || this.isShowRecommendUI == appState.isShowRecommendUI())
                && (appState.isIgnoreTimeLiveUI() || this.isTimeLiveUI == appState.isTimeLiveUI())
                && this.isChangingLive == appState.isChangingLive()
                && this.curPlayType.equals(appState.curPlayType());
        return rtVal;
    }

    private boolean isProcTTL = false;

    public boolean isProcTTL() {
        return isProcTTL;
    }

    public void setProcTTL(boolean procTTL) {
        isProcTTL = procTTL;
    }

    // 是否可以显示预约提醒
    public boolean isShowAppUI(){
        // curLiveType = 当前的直播状态 Live = 直播流 时移 = Time 回看 = Back
        // curPlayType 当前的播放界面类型(直播 = Live 点播 = Vod)
//        boolean rtVal = this.isFullScreen && this.isFocus && this.curLiveType.equals("Live")
//                && this.curPlayType.equals("Live");
        boolean rtVal = this.curPlayType.equals("Live");
        return rtVal;
    }


    // 预约的列表对象
    private BillAppointmentContainer billAppointmentContainer;

    // 循环发送心跳包
    private TTLPlayProc ttlPlayProc;

    public BillAppointmentContainer getBillAppointmentContainer() {
        return billAppointmentContainer;
    }

    // 当前的直播界面顶层菜单的列表
    private List<TopMenu> topMenuList;

    public List<TopMenu> getTopMenuList() {
        return topMenuList;
    }

    public List<IListViewShowItem> getTopListViewShowItem() {
        List<IListViewShowItem> list = new ArrayList<IListViewShowItem>();
        list.addAll(topMenuList);
        return list;
    }


    // 获得频道分类列表（直播）
    private List<ChannelType> channelTypeList;
    public List<ChannelType> getChannelTypeList() {
        ChannelType.setCurType("live");
        return channelTypeList;
    }

    // 获得直播历史
    public List<ChannelType> getHisChannelTypeList() {
        ChannelType.setCurType("his");
        return channelTypeList;
    }

    private BookmarkList bookmarkList;

    public BookmarkList getBookmarkList(){
        return this.bookmarkList;
    }

    // 获得直播频道下的频道类别列表
    public List<IListViewShowItem> getChannelTypeListViewShowItem(String code) {
        List<IListViewShowItem> list = new ArrayList<IListViewShowItem>();
        if(code.equals("live")) {   // 直播频道
            list.addAll(getChannelTypeList());
        }
        if(code.equals("his")){     // 回看频道
            list.addAll(getHisChannelTypeList());
        }
        if(code.equals("recent")){  // 常看频道
            List<ChannelRecords> records = this.getChannelDLinkList().getChannelHis().getList();
            Collections.sort(records);
            Collections.reverse(records);
            for(int i = 0; i < records.size(); i++){
                Channel channel = this.getChannelDLinkList().findChannelByID(records.get(i).getChannelID());
                if(channel != null){
                    list.add(channel);
                }
            }
        }
        if(code.equals("app")) {  // 预约频道
            this.getBillAppointmentContainer().initData();
            list.addAll(this.getBillAppointmentContainer().getBillAppointmentList());
        }
        if(code.equals("hot")){    // 热播频道
            if(this.hotChannelList == null || this.hotChannelList.size() == 0){
                initHotChannelList();
            }
            list.addAll(this.hotChannelList);
        }
        else {
            //list.addAll(channelDLinkList.seachByCategoryCode("ALL"));
        }
        return list;
    }

    // 热播频道的参数列表
    private InitHotChannelListData hotChannelListDataargs;
    private List<Channel> hotChannelList = new ArrayList<Channel>();

    // 设置热播频道的参数
    public void setHotChannelListDataArgs(InitHotChannelListData args){
        hotChannelListDataargs = args;
    }

    private void initHotChannelList(){
        if(hotChannelListDataargs != null
                && hotChannelListDataargs.getData() != null
                && hotChannelListDataargs.getData().size() > 0){
            hotChannelList.clear();
            for(int i = 0; i < hotChannelListDataargs.getData().size();i++){
                Channel channel = this.findChannelByID(hotChannelListDataargs.getData().get(i).getChannelID());
                if(channel != null){
                    hotChannelList.add(channel);
                }
            }
        }
    }

    public void syncHotChannelList(){
        initHotChannelList();
    }



    // 频道列表
    private com.iptv.grape.domain.ChannelDLinkList channelDLinkList;

    public ChannelDLinkList getChannelDLinkList() {
        return channelDLinkList;
    }



    // 节目单集合
    private ChannelBillList billList = new ChannelBillList();

    public ChannelBillList getBillList() {
        return billList;
    }

    // 点播观看历史
    private AssetPlayDataList assetPlayDataList;
    public AssetPlayDataList getAssetPlayDataList(){
        return this.assetPlayDataList;
    }
    // 设置当前的播放记录指针
    private AssetPlayData curPlayVod;
    public void setCurPlayVod(AssetPlayData curPlayVod){
        this.curPlayVod = curPlayVod;
    }
    public AssetPlayData getCurPlayVod(){
        return this.curPlayVod;
    }

    private String getString(int id){
       return RunTimeApplication.getCurApp().getResources().getString(id);
    }
    // 初始化数据辅助线程
    private Thread threadInitData;
    // 初始化的辅助函数
    private void initHelp(Context context){
        threadInitData = new Thread() {
            public void run() {
                try {
                    // 构造UserInfo对象 构造失败通知MainAct弹出对话框
                    BuildRes buildRes = UserInfo.buildUserInfo();
                    if(!buildRes.isSuccess()){
                        AppLog.getCurLog().e(buildRes.getException().getMessage());
                        // 构造失败通知MainAct弹出对话框
                        grapeInitBack.initDlg(GrapeInitBack.DLG_USERINFO_FIAL,getString(R.string.dlg_userinfo_fail));
                        return;
                    }
                    boolean isFromFileUserInfo = (boolean)buildRes.getArgs();
                    // 认证UserInfo
                    // 认证失败 通知MainAct弹出对话框 认证成功则需要开启定时器
                    LoginResult loginResult = NetworkService.getInstance().loginAsync();
                    if(loginResult == null){
                        if(!isFromFileUserInfo) {
                            // 认证失败 无响应  并且UserInfo 的信息不是从文件中读出来的 通知MainAct弹出对话框 认证失败
                            grapeInitBack.initDlg(GrapeInitBack.DLG_AUTH_N0RESPONSE,getString(R.string.dlg_auth_noresponse));
                            AppLog.getCurLog().out("300 认证失败 无响应  并且UserInfo 的信息不是从文件中读出来");
                            return;
                        }
                        else {
                            SharedUtil.put(SharedUtil.FILE_DEFUALT,"auth_time", (System.currentTimeMillis()/1000));
                            grapeInitBack.goOnAuth(GrapeInitBack.AUTH_301);
                            // 设置定时器 下次在继续认证
                            AppLog.getCurLog().out("301 设置定时器 下次在继续认证");
                        }
                    }else {
                         if(loginResult.getRtCode().equals("S")) {
                            // 认证成功
                            UserInfo.setLoginInfo(loginResult.getData());
                            // 设置定时器 下次在继续认证
                             SharedUtil.put(SharedUtil.FILE_DEFUALT,"auth_time", (System.currentTimeMillis()/1000));
                            grapeInitBack.goOnAuth(GrapeInitBack.AUTH_SUCCESS);
                            AppLog.getCurLog().out("200 UserInfo Ack OK");
                        } else if(loginResult.getRtCode().equals("F")){
                            AppLog.getCurLog().e("login===>>5555");
                            // 明确了错误 停机 或者 销户 或者错误的状态 通知MainAct弹出对话框 显示出失败原因
                            String reason =loginResult.getReason();
                            switch (reason){
                                case "UserDowntime":
                                    grapeInitBack.initDlg(GrapeInitBack.DLG_LOGIN_F,"您的账户已停机");
                                    break;
                                case"UserAccountCancellation":
                                    grapeInitBack.initDlg(GrapeInitBack.DLG_LOGIN_F,"您的账户已销户");
                                    break;
                                case"UserStatusError":
                                    grapeInitBack.initDlg(GrapeInitBack.DLG_LOGIN_F,"用户状态异常 数据错误或者程序BUG 需要联系厂家");
                                    break;
                            }

                            UserInfo.setLoginInfo(loginResult.getData());
                            AppLog.getCurLog().out("303 UserInfo " + loginResult.getReason());
                            return;
                        }else {
                            // 服务器无法给出认证结果（服务内部异常）
                            if(!isFromFileUserInfo) {
                                grapeInitBack.initDlg(GrapeInitBack.DLG_LOGIN_NULL,getString(R.string.dlg_login_null));
                                // 并且UserInfo 的信息不是从文件中读出来的 通知MainAct弹出对话框 认证失败请重新启动在尝试
                                AppLog.getCurLog().out("304 UserInfo 的信息不是从文件中读出来的 通知MainAct弹出对话框 认证失败请重新启动在尝试");

                                return;
                            }
                            else {
                                SharedUtil.put(SharedUtil.FILE_DEFUALT,"auth_time", (System.currentTimeMillis()/1000));
                                grapeInitBack.goOnAuth(GrapeInitBack.AUTH_305);
                                // 设置定时器 下次在继续认证
                                AppLog.getCurLog().out("305 设置定时器 下次在继续认证");
                            }
                        }
                    }
                    AppLog.getCurLog().e(UserInfo.curUserInfo().toString());
                    if(UserInfo.curUserInfo().isUserBlack()){
                        grapeInitBack.initDlg(GrapeInitBack.DLG_BLACKLIST,getString(R.string.dlg_blacklist));
                        // 用户是黑名单 通知MainAct弹出对话框 显示出失败原因
                        return;
                    }
                    if(!UserInfo.curUserInfo().isNormal()){
                        grapeInitBack.initDlg(GrapeInitBack.DLG_AHNORMAL_STATE,getString(R.string.dlg_ahnormal));
                        // 用户是非正常状态 通知MainAct弹出对话框 显示出失败原因
                        return;
                    }
                    initChannelTypeList();
                    AppLog.getCurLog().out("初始化频道分类列表成功");
                    initChannelData();
                    AppLog.getCurLog().out("初始化频道列表成功");
                    initChannelBillData();
                    AppLog.getCurLog().out("初始化节目单列表成功");
                    initBillAppointmentData();
                    AppLog.getCurLog().out("初始化预约列表成功");

                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 通知MainAct 撤销启动图
            }
        };




        ttlPlayProc = new TTLPlayProc();
        isProcTTL = false;
        dataProc = new DataProc();
        channelDLinkList = new com.iptv.grape.domain.ChannelDLinkList();
        this.isShowLiveMenu = false;
        this.isFullScreen = false;
        this.isFocus = false;
        this.isPlaying = false;
        this.isShowChannelBillUI = false;
        this.isShowVodMenu = false;
        this.isShowRecommendUI = false;
        this.isTimeLiveUI = false;
        this.isChangingLive = false;
        this.curLiveType = "Live";
        this.curPlayType = "Live";
        quitFullScreenStopPlay = false;
        curEnvironment="U";
        // 直播的频道菜单Fragment对象
        liveMenuFragment = null;
        // 回看界面
        channelBillFragment = null;
        // 点播的进度条界面
        vodFragment = null;
        // 直播底部推荐
        recommendFragment = null;
        // 时移底部进度条
        timeLiveFragment = null;

    }
    private GrapeInitBack grapeInitBack;
    public void setGrapeInitBack(GrapeInitBack grapeInitBack){
        this.grapeInitBack = grapeInitBack;
    }
    // 初始化
    public void init(Context context) {

        initHelp(context);


        String topMenuJson = ReadJsonFile.readFileByAssets("topMenu.json", context);
        AppConfig.init(context);
        Type type = new TypeToken<List<TopMenu>>() {
        }.getType();
        topMenuList = new Gson().fromJson(topMenuJson, type);

        threadInitData.start();


        this.assetPlayDataList = AssetPlayDataList.unSerializeToFile();
        if (this.assetPlayDataList.isEmpty()) {
            this.assetPlayDataList.init();
        }

        this.bookmarkList = BookmarkList.unSerializeToFile();
        if (this.bookmarkList.isEmpty()) {
            this.bookmarkList.init();
        }

        // 开始心跳处理
        ttlPlayProc.init();
    }


    // 将当前活动的BaseActivity保存起来
    public void registerActivity(BaseActivity activity, XMediaPlayer mediaPlayer){
        this.curActivity = activity;
        this.curMediaPlayer = mediaPlayer;
    }

    // 获得最后一次播放的 直播频道
    public String getLastPlayChannel(){
        return this.getChannelDLinkList().getChannelHis().getCurPlayChannel().getPlayUrl();
    }
    // 根据ID来找到对应的频道
    public Channel findChannelByID(String channelID){
         for(Channel channel: this.getChannelDLinkList().getChannels()){
             if(channel.getKeyID().equals(channelID)){
                 return channel;
             }
         }
         return null;
    }

    // 根据频道号来找到对应的频道
    public Channel findChannelByNo(int channelNo){
        for(Channel channel: this.getChannelDLinkList().getChannels()){
            AppLog.getCurLog().out(channel.getName());
            if(channel.getChannelNo() == channelNo){
                return channel;
            }
        }
        return null;
    }



    // 初始化频道分类列表数据结构
    private void initChannelTypeList(){
        try {
            channelTypeList = ChannelType.unSerializeToFile();
            if(channelTypeList == null){
                channelTypeList = NetworkService.getInstance().getChannelTypeListAsync();
                if(channelTypeList !=null){
                    Collections.sort(channelTypeList);
                    ChannelType.serializeToFile(channelTypeList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 初始化频道列表数据结构
    private void initChannelData(){
        try {
            channelDLinkList.readFileInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 初始化节目单辅助方法
    private void initChannelBillData(){
        try {
            // 频道构建领域模型
            billList.init();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private BillAppointmentProc billAppointmentProc = new BillAppointmentProc();
    // 从文件中加载已经预约的对象
    private void initBillAppointmentData(){
        try {
            this.billAppointmentContainer = BillAppointmentContainer.unSerializeToFile();
            // 开启预约定时器
            //billAppointmentProc = new BillAppointmentProc();
            billAppointmentProc.init();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }






    public void setPlaying(boolean playing) {
        isPlaying = playing;
    }

    public void setFocus(boolean focus) {
        isFocus = focus;
    }

    public void setFullScreen(boolean fullScreen) {
        isFullScreen = fullScreen;
    }


    // 数据探针
    private DataProc dataProc;

    @Subscribe()
    public void onMoonEvent(EventArgs eventArgs){


    }


}
